from fastapi import APIRouter, Query, UploadFile
from tortoise.transactions import in_transaction

from app.controllers.exams.exam import exam_controller
from app.controllers.exams.question import question_controller
from app.controllers.exams.user_answer import user_answer_controller
from app.models import Exam
from app.schemas.exams import ExamCreate, ExamUpdate, QuestionCreate, QuestionUpdate
from app.schemas.base import Success, SuccessExtra, Fail
from tortoise.expressions import Q
from app.utils.upload import upload_image, upload_file

exam_router = APIRouter()


@exam_router.post("/create", summary=f"创建试卷")
async def do_create(
        data_in: ExamCreate,
):
    # 使用事务
    async with in_transaction() as transaction:
        ret = await exam_controller.do_create(obj_in=data_in)
        for data in data_in.questions:
            question = data['question']
            select_list = []
            score_list = []
            try:

                for i in range(1, 5):  # 遍历1到4
                    select_key = f'select{i}'
                    score_key = f'score{i}'
                    select_value = data[select_key]
                    score_value = data[score_key]
                    if select_value and select_value:
                        select_list.append(f"{select_value}|{score_value}")  # 格式化为 "A:1"
                        score_list.append(f"{select_value}|{score_value}")  # 格式化为 "A:1
            except Exception as e:
                return {"msg": f"错误{e}"}

            question_data = QuestionCreate(
                exam_id=ret.id,
                question=question,
                selects=select_list,
                answer=score_list
            )
            ret2 = await question_controller.do_create(obj_in=question_data)
            data["id"] = ret2.id

        await Exam.filter(id=ret.id).update(questions=data_in.questions)

    return Success(msg="创建成功")


@exam_router.post("/update", summary=f"更新试卷")
async def do_update(
        data_in: ExamUpdate,
):
    async with in_transaction() as transaction:
        await exam_controller.do_update(obj_in=data_in)

        for data in data_in.questions:
            question = data['question']
            select_list = []
            score_list = []
            try:
                for i in range(1, 5):  # 遍历1到4
                    select_key = f'select{i}'
                    score_key = f'score{i}'
                    select_value = data[select_key]
                    score_value = data[score_key]
                    if select_value and select_value:
                        select_list.append(f"{select_value}|{score_value}")  # 格式化为 "A:1"
                        score_list.append(f"{select_value}|{score_value}")  # 格式化为 "A:1
            except Exception as e:
                return {"msg": f"错误{e}"}

            question_data = QuestionUpdate(
                id=data['id'],
                exam_id=data_in.id,
                question=question,
                selects=select_list,
                answer=score_list
            )
            await question_controller.do_update(obj_in=question_data)

    return Success(msg="更新成功")


@exam_router.delete("/delete", summary=f"删除试卷")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await exam_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")


@exam_router.get("/list", summary=f"查看试卷列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        title: str = Query(None, description=f"名称"),
):
    q = Q()
    if title:
        q &= Q(title__contains=title)
    total, data = await exam_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@exam_router.get("/list_space", summary=f"查看试卷列表")
async def list_space():
    data_objs = await exam_controller.data_list()
    data = []
    for level in data_objs:
        if level:
            data.append({"value": level['id'], "label": level['title']})
    return Success(data=data)

@exam_router.get("/answer_list", summary=f"查看头皮档案")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        exam_id: int = Query(0, description=f"问卷id"),
        customer_id = Query(0, description="用户id"),
):
    q = Q(user_id=customer_id)
    if exam_id:
        q &= Q(exam_id=exam_id)
    total, data = await user_answer_controller.do_list(page=page, page_size=page_size, search=q)

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@exam_router.post("/file", summary="上传缩略图")
async def file_content(file: UploadFile):
    url = await upload_file(file, "exams/exam")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)




